# -*- coding: utf-8 -*-
import json
import math
import copy
from pyquery import PyQuery
from crecgec.matcher import *
from crecgec.items import crecgecSku, crecgecFull
from zc_core.model.items import Catalog, ItemDataSupply
from zc_core.pipelines.helper.catalog_helper import CatalogHelper


# 解析catalog列表
def parse_catalog(response):
    cats = list()
    text = response.text
    json_data = json.loads(re.search('''application/json">(.*)</script><script nomodule=''', text).group(1))
    data_list = json_data.get('props', {}).get('pageProps', {}).get('props', {}).get('categoryList', {}).get('data', {})
    for data1 in data_list:
        # TODO 一级分类
        cat1_id = data1.get('bndFirstId')
        cat1_name = data1.get('nodeName')
        cat11 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat11)
        for data2 in data1.get('child'):
            # TODO 二级分类
            cat2_id = data2.get('bndSecondId')
            cat2_name = data2.get('nodeName')
            data = data2.get('child')
            if data:
                cat2_id = data[0].get('bndSecondId')
            cat22 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat22)
            for data3 in data2.get('child'):
                # TODO 三级分类
                if data3.get('nodeType') == "1":
                    cat3_id = data3.get('bndThirdId')
                    cat3_name = data3.get('nodeName')
                    cat33 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                    cats.append(cat33)
    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 维度：解析sku列表页数
def parse_total_page(response):
    total_page = json.loads(response.text).get('data', {}).get('page', {}).get('totalPage', 1)
    return total_page


# 维度：品牌，解析sku列表页数
def parse_brand_total_page(response):
    page_json = json.loads(response.text)
    total_page = page_json['result']['pageTotal']

    return total_page


# 分割价格
def split_price(price_range):
    price_list = price_range.split('-')
    start = int(price_list[0])
    end = int(price_list[1])
    mean = start + math.floor((end - start) / 2)
    if start != end:
        return [str(start) + "-" + str(mean), str(mean) + "-" + str(end)]
    else:
        return []


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    data_list = json.loads(response.text).get('data', {}).get('page', {}).get('resultList', [])
    skus = list()
    items = list()
    cat_helper = CatalogHelper()
    for i in data_list:
        sku = crecgecSku()
        sku['skuId'] = str(i.get('goodsId')) + "_" + str(i.get('itemId'))
        sku['batchNo'] = batch_no
        sku['catalog3Id'] = i.get('b3CatId')
        sku['catalog2Id'] = i.get('b2CatId')
        sku['catalog1Id'] = i.get('b1CatId')
        cat_helper.fill(sku)
        sku['skuName'] = i.get('goodsShowName')
        sku['supplierName'] = i.get('busiName')
        sku['supplierId'] = i.get('busiId')
        sku['skuImg'] = i.get('mSpicPath')
        sku['soldCount'] = i.get('sales')
        sku['originPrice'] = i.get('mktPrice')
        sku['salePrice'] = i.get('price')
        sku['brandName'] = i.get('brandName')
        skus.append(sku)
    items = copy.deepcopy(skus)
    return skus, items


def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    jpy = PyQuery(response.text)
    result = crecgecFull()
    # 批次编号
    result['batchNo'] = batch_no
    result['skuId'] = sku_id

    result['skuCode'] = jpy('.collect___129v_').text().strip().split()[0].replace('商品编号：', '')
    result['supplierSkuCode'] = jpy('.collect___129v_').text().strip().split()[1].replace('供应商商品编号：', '')
    result['supplierSkuId'] = jpy('.collect___129v_').text().strip().split()[1].replace('供应商商品编号：', '')
    minBuy = jpy('.label___Dwa7l p:contains("最小起订：")').text().replace('\n', '').replace(
        '最小起订：',
        '')
    if minBuy:
        result['minBuy'] = minBuy
    return result


def full_catalog(response):
    meta = response.meta
    skuId = meta.get('skuId')
    catalog3_id = meta.get('catalog3Id')
    batch_no = meta.get('batchNo')
    result = ItemDataSupply()
    jpy = PyQuery(response.text)
    result['skuId'] = skuId
    result['batchNo'] = batch_no
    catalog_list = [data for data in jpy('.content_header p a').items()]
    if catalog_list.__len__() == 4:
        catalog1Id = match_catalogId(catalog_list[1].attr('href'), 1)
        if catalog1Id:
            catalog1Name = catalog_list[1].text().replace('> ', '')
            result['catalog1Id'] = catalog1Id
            result['catalog1Name'] = catalog1Name
        catalog2Id = match_catalogId(catalog_list[2].attr('href'), 2)
        if catalog2Id:
            catalog2Name = catalog_list[2].text().replace('> ', '')
            result['catalog2Id'] = catalog2Id
            result['catalog2Name'] = catalog2Name
        catalog3Id = match_catalogId(catalog_list[3].attr('href'), 3)
        if catalog3Id:
            catalog3Name = catalog_list[3].text().replace('> ', '')
            result['catalog3Id'] = catalog3Id
            result['catalog3Name'] = catalog3Name
    else:
        print('异常', )

    return result
